package com.shanshan.crowd.mvc.interceptor;

import com.shanshan.crowd.constant.CrowdConstant;
import com.shanshan.crowd.exception.AccessForbiddenException;
import com.shanshan.crowd.exception.LoginFailedException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description
 * @ClassName LoginInterceptor
 * @Author 山山大魔王
 * @Date 2022/7/21 17:17
 * @Version 1.0
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.通过request对象获取session对象
        HttpSession session = request.getSession();
        // 2.尝试从session域中获取admin对象
        Object admin = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
        // 3.判断admin对象是否为空
        if (admin == null){
            // 4.抛出异常
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
        }

        // 5.如果admin不为空，则放行
        return true;
    }
}
